<?php


namespace App\Http\Controllers\Admin;


use App\Models\Admin;
use App\Models\Province;
use App\Transformers\ProvinceTransformer;
use App\Transformers\SimpleTransformer;
use Dingo\Api\Http\Request;

class AdminController extends BaseController
{

    public function index() {
        $province = Province::paginate(10);
        return $this->response->paginator($province, new ProvinceTransformer(['city']));

        $users = Admin::paginate();
        return $this->response->paginator($users, new SimpleTransformer(['id']));
    }

    public function store(Request $request) {
        $input = $request->input();
        $this->validate($request, [
            'phone'   => 'required|numeric|regex:/^1[3456789][0-9]{9}$/|unique:admins',
            'username'  => 'required|min:4|max:14|unique:admins',
            'password'  => 'required|confirmed|min:6|max:14',
            'password_confirmation' => 'required|same:password'
        ]);
        $input['password'] = bcrypt($input['password']);
        if ($admin = Admin::create($input)){
            return $this->success(['id' => $admin->id]);
        }
        return $this->failed('创建失败');
    }

    public function updatePwd(Request $request) {
        $input = $request->input();
        $this->validate($request, [
//            'old_password'  => 'required',
            'password'  => 'required|confirmed|min:6|max:14',
            'password_confirmation' => 'required|same:password'
        ]);
        $user = $this->getUser();
        $user->password = bcrypt($input['password']);
        if ($user->save()){
            auth()->refresh();
            $token = auth()->login($user);
            return $this->respondWithToken($token);
        }
        return $this->failed('创建失败');
    }

    public function logout(Request $request) {
        auth()->logout();
//        auth()->refresh();
        return $this->success([]);
    }


}

